package com.boot.kafka.jpa.elasticsearch.config;


import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.ArrayList;
import java.util.List;


@Slf4j
@Configuration
public class ElasticsearchConfig {

    static final String DEFAULT_HOST = "localhost";

    static final int DEFAULT_PORT = 9200;

    @Autowired
    ElasticsearchProperties properties;

    @Primary
    @Bean
    public RestHighLevelClient restHighLevelClient() {

        List<HttpHost> hostList = new ArrayList<>();
        if (properties.getHosts() != null) {
            properties.getHosts().forEach(h -> {
                String[] hp = h.split(":");
                if (hp.length == 2) {
                    hostList.add(new HttpHost(hp[0], Integer.parseInt(hp[1]), HttpHost.DEFAULT_SCHEME_NAME));
                }
            });
        } else {
            hostList.add(new HttpHost(DEFAULT_HOST, DEFAULT_PORT, HttpHost.DEFAULT_SCHEME_NAME));
        }

        RestClientBuilder builder = RestClient.builder(hostList.toArray(new HttpHost[0]));
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        if (properties.getUser() != null) {
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(properties.getUser(), properties.getPassword()));
        }
        builder.setHttpClientConfigCallback(callback -> callback.setDefaultCredentialsProvider(credentialsProvider));

        return new RestHighLevelClient(builder);
    }

}
